package com.breeze.components.mybatis.dto;

import com.breeze.components.core.util.json.serializer.LongTypeSerializer;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.mybatisflex.core.paginate.Page;
import io.swagger.v3.oas.annotations.media.Schema;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.stream.Collectors;
import lombok.Data;
import lombok.experimental.Accessors;
import org.springframework.beans.BeanUtils;

/**
 * @author breeze
 */
@Data
@Accessors(chain = true)
public class TotalDTO<T> {

  @Schema(title = "列表")
  List<T> list;

  @Schema(title = "总数量")
  @JsonSerialize(using = LongTypeSerializer.class)
  private Long total;

  public static <T> TotalDTO<T> wrapper(List<T> list) {
    TotalDTO<T> dto = new TotalDTO<>();
    dto.setList(list);
    dto.setTotal(list != null ? list.size() : 0L);
    return dto;
  }

  public static <T> TotalDTO<T> wrapper(Page<T> page) {
    TotalDTO<T> dto = new TotalDTO<>();
    dto.setTotal(page.getTotalRow());
    dto.setList(page.getRecords());
    return dto;
  }

  public static <R, T> TotalDTO<T> wrapper(Page<R> page, Class<T> tClass) {
    TotalDTO<T> dto = new TotalDTO<>();
    dto.setTotal(page.getTotalRow());
    dto.setList(
        page.getRecords().stream()
            .map(
                s -> {
                  T newInstance;
                  try {
                    newInstance = tClass.getDeclaredConstructor().newInstance();
                  } catch (InstantiationException
                      | IllegalAccessException
                      | InvocationTargetException
                      | NoSuchMethodException e) {
                    throw new RuntimeException(e);
                  }
                  BeanUtils.copyProperties(s, newInstance);
                  return newInstance;
                })
            .collect(Collectors.toList()));
    return dto;
  }
}
